package com.xiaohai.demo.touting;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 发布订阅模式，
 * 生产者
 */
public class Productor {

    private static  String QUEUE_INFO_EMAIL ="queue_info_emain";
    private static  String QUEUE_INFO_SMS ="queue_info_sms";
    private static  String EXCHANGE_FANOUT_INFO ="exchange_fanout_info2";

    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("127.0.0.1");
        factory.setPort(5672);
        factory.setUsername("guest");
        factory.setPassword("guest");
        factory.setVirtualHost("/");


        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        /**
         * 声明交换机，名称
         * 交换机类型
         * 交换机类型，fanout、topic、direct、headers
         */
        channel.exchangeDeclare(EXCHANGE_FANOUT_INFO, BuiltinExchangeType.DIRECT);
        /**
         * 声明队列
         *
         * 1，队列名称
         * 2，是否持久化
         * 3，是否独占此队列
         * 4，不在使用时，是否自动删除
         * 5，队列参数
         */
        channel.queueDeclare(QUEUE_INFO_EMAIL,true,false,false,null);
        channel.queueDeclare(QUEUE_INFO_SMS,true,false,false,null);

        //交换机 和队列绑定
        channel.queueBind(QUEUE_INFO_SMS,EXCHANGE_FANOUT_INFO,QUEUE_INFO_SMS);
        channel.queueBind(QUEUE_INFO_EMAIL,EXCHANGE_FANOUT_INFO,QUEUE_INFO_EMAIL);

        //发送消息(邮件消息,短信消息)
        for (int i = 0; i < 10; i++) {
            String mess ="information for"+ i;
            //交换机名称，路由key,消息属性，消息内容
            channel.basicPublish(EXCHANGE_FANOUT_INFO,QUEUE_INFO_EMAIL,null,mess.getBytes());

            System.out.println("Send email Message is:'" + mess + "'");

            String mess2 ="information for"+ i;
            //交换机名称，路由key,消息属性，消息内容
            channel.basicPublish(EXCHANGE_FANOUT_INFO,QUEUE_INFO_SMS,null,mess2.getBytes());

            System.out.println("Send sms Message is:'" + mess + "'");
        }


        channel.close();
        connection.close();

    }

}
